package com.xhwl.logistics.validate.parking;

import com.xhwl.logistics.service.impl.VehicleParkingLotServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.util.Objects;

public class ValidParkingLotConstraintValidator implements ConstraintValidator<ValidParkingLotConstraint, Object> {

    private static final String methodNameForProject = "getProjectId";
    private static final String methodNameForParkingLot = "getParkingLotName";

    @Autowired
    private VehicleParkingLotServiceImpl vehicleParkingLotService;

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        Integer projectId;
        String parkingLotName;

        Method methodForGetProjectId = ReflectionUtils.findMethod(object.getClass(), methodNameForProject);
        Method methodForGetParkingLotName = ReflectionUtils.findMethod(object.getClass(), methodNameForParkingLot);

        Assert.notNull(methodForGetProjectId, "验证的对象不具有项目id，因此不能使用车场验证");

        Object objectForProjectId = ReflectionUtils.invokeMethod(methodForGetProjectId, object);
        Assert.isInstanceOf(Integer.class, objectForProjectId, "项目id必须是Integer类型和不能为null");
        projectId = (Integer)objectForProjectId;
        if (Objects.isNull(methodForGetParkingLotName)) {
            vehicleParkingLotService.queryParkingLot(projectId, null);
        } else {
            Object objectForParkingLotName = ReflectionUtils.invokeMethod(methodForGetParkingLotName, object);
            if (Objects.isNull(objectForParkingLotName)) {
                vehicleParkingLotService.queryParkingLot(projectId, null);
            } else {
                Assert.isInstanceOf(String.class, objectForParkingLotName, "车场名称必须是String类型");
                parkingLotName = (String)objectForParkingLotName;

                vehicleParkingLotService.queryParkingLot(projectId, parkingLotName);
            }
        }

        return true;
    }

}
